
package org.finegold.core.delivery;


import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.finegold.core.delivery.props.DeliveryProperties;
import org.finegold.core.http.HttpRequest;
import org.finegold.core.tool.api.R;


/**
 * 顺丰下单类
 *
 * @author QinXueFeng
 */
@AllArgsConstructor
@Slf4j
public class SfDeliveryTemplate implements DeliveryTemplate {

	private final String baseUrl;

	public SfDeliveryTemplate(DeliveryProperties deliveryProperties) {
		this.baseUrl= deliveryProperties.getIsTest() ? deliveryProperties.getTestUrl() : deliveryProperties.getProdUrl();
	}


	@Override
	public <T> R<String> addDeliveryOrder(T data) {
		String url = baseUrl+"/addDeliveryOrder";
		log.info("地址{}",url);
		R<String> result = getStringR(data, url);
		return result;
	}

	@Override
	public <T> R<String> updateOrder(T data) {
		String url = baseUrl+"/updateOrder";
		R<String> result = getStringR(data, url);
		return result;
	}

	@Override
	public <T> R cancelOrder(T data) {
		String url = baseUrl+"/batchCancelOrder";
		R<String> result = getStringR(data, url);
		return result;
	}

	@Override
	public <T> R<String> getRouteService(T data) {
		String url = baseUrl+"/getRouteService";
		R<String> result = getStringR(data, url);
		return result;
	}

	@Override
	public <T> R<String> generateOrder(T data) {
		String url = baseUrl+"/printExpressSheet";
		R<String> result = getStringR(data, url);
		return result;
	}

	@Override
	public <T> R<String> receiptFlagPhoto(T data) {
		String url = baseUrl+"/printExpressSheet";
		R<String> result = getStringR(data, url);
		return result;
	}

	private <T> R<String> getStringR(T data, String url) {
		R<String> result = new R<String>();
		HttpRequest.post(url)
			.bodyJson(data)
			.execute()
			.onFailed((request, e) -> {
				log.error("识别出错,错误信息：{}，详细内容：{}", e.getMessage(), e);
				result.setCode(-1);
				result.setMsg("error");
				result.setData(e.getMessage());
			})
			.onSuccessful((str) -> {
				JSONObject resultJson = JSONObject.parseObject(str.asString());
				result.setCode(resultJson.getInteger("status"));
				result.setSuccess(resultJson.getInteger("status") == 200 ? true : false);
				result.setMsg(resultJson.getString("msg"));
				result.setData(resultJson.getString("data"));
				return result;
			});
		return result;
	}
}
